<template>
  <div class="app-container">

      <el-form class="main-form" v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" >
           <el-form-item label="账号ID：" prop="账号ID">
            <el-input v-model="queryParams['账号ID']" placeholder="请输入账号ID" />
          </el-form-item>

         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
            >新增</el-button>
            <el-button
            plain
            type="success"
            icon="refresh"
             @click="findList">刷新</el-button>
         </el-col>

      </el-row>


      <el-table class="data-list" v-loading="loading" :data="records">
         <el-table-column v-for="(fieldLabel) in fieldLabels" :label="fieldLabel" align="center" :prop="fieldLabel">
            <template #default="scope">
              <template v-if="fieldLabel.endsWith('日期')">
                {{ $filters.date(scope.row[fieldLabel], 'yyyy-MM-dd') }}
              </template>
              <template v-else-if="fieldLabel === '偏好设置'">
                <preference-view :value="scope.row[fieldLabel] ? JSON.parse(scope.row[fieldLabel]) : null" />
              </template>
              <template v-else>
                {{ scope.row[fieldLabel] }}
              </template>

            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row, scope.$index)" >删除</el-button>

            </template>
         </el-table-column>
      </el-table>

      <preference-form v-if="form" v-model:item="form" @success="onSubmitSuccess" />


   </div>
</template>
<script setup lang="ts">
import {reactive, ref, toRefs, onMounted } from 'vue'
import * as accountService from '@/api/service/AccountService'
import PreferenceView from '@/components/feishu/PreferenceView.vue';
import PreferenceForm from './form.vue'

defineOptions({ name: "PreferenceIndex" });

const globalVal = globalThis as any;
const fieldLabels = ref<string[]>([])
const records = ref<any>([])
const loading = ref(false)
const showSearch = ref(true)
const form = ref<any|null>(null)



const data = reactive({
  form: {},
  queryParams: {
    '账号ID': ''
  }
});

const { queryParams } = toRefs(data)



/** 查询列表 */
async function findList() : Promise<any> {
  //loading.value = true;
  let list = [];
  let labels:string[] = ['账号ID'];
  const conditions:any[] = <any>[];

  if(data.queryParams['账号ID']){
    conditions.push({
      field_name: '账号ID',
      operator: 'is',
      value: [data.queryParams['账号ID']]
    })
  }

  const queryBody = {
    filter: {
      conjunction:'and',
      conditions: conditions
    }
  }

  loading.value = true;
  for await (const page of await accountService.findList(queryBody)){
    const items = page.items.map(item => {
      const result = globalVal.parseFeishuRecord(item);
      let keys = Object.keys(result);
      for(const key of keys){
        if(!labels.includes(key) && !['序号', 'recordId'].includes(key)){
          labels.push(key);
        }
      }
      return result;
    })
    list = list.concat(items)
    records.value = list;
    fieldLabels.value = labels;
    loading.value = false;
  }
}

/** 搜索按钮操作 */
function handleQuery(): void {
  findList()
}

/** 提交成功 */
function onSubmitSuccess():void{
  findList()
}

/**
 * 添加
 */
function handleAdd():void{
  form.value = {
  }
}

/**
 * 修改
 */
function handleUpdate(item:any):void{
  form.value = {
    ... item
  }
}

/**
 * 删除
 */
function handleDelete(item:any, index:number):void{
  globalVal.showConfirm({
    message: '确认要删除该记录',
    confirm:(done)=>{
      globalVal.showLoading();
      accountService.removeRecord(item.recordId).then(()=>{
        globalVal.success('删除成功');
        records.value.splice(index, 1)
      }).finally(()=>{
        globalVal.hideLoading();
        done && done()
      });
    }
  })

}


onMounted(() => {
  findList();
})

</script>

<style lang="scss" scoped>
.app-container{
  display: flex;
  flex-direction: column;
}
.app-tables{
  display: flex;
  align-items: center;
  h4{
    font-size: 14px;
    line-height: 14px;
    margin:0;
    padding: 0;
    margin-right: 40px;
    line-height: 36px;
    white-space: nowrap;

  }
  .table-item{
    margin-right: 20px;
    label{
      font-size: 14px;
      margin-right: 10px;
      line-height: 36px;
      font-weight: bold;
    }
  }

}
.main-form{



  .category-second{
    margin-left: 20px;
  }
}

.data-list{
  flex:1;
}

</style>
